<template>
  <div class="container">
    <div class="header">
      <div class="left">
        <div class="line"></div>
        <h2>请假记录</h2>
        <el-input v-model="classSearchInput" placeholder="请输入姓名" style="width: 150px" class="className"
          v-if="roleId != '3' && roleId != '5'&& roleId != '4'"></el-input>
        <el-date-picker v-model="currentYearMonth" type="month" placeholder="选择查询时间" style="width: 150px"
          value-format="YYYY-MM" class="className"></el-date-picker>
        <div style="position: relative">
          <el-button @click="handleSearch" class="search">搜索</el-button>
          <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
        </div>
      </div>
      <div class="right" v-if="roleId == 3 || roleId == 5 ||roleId==4">
        <p @click=apply>申请</p>
        <el-dialog v-model="dialogVisible" :showClose="false">
          <header class="el-dialog__header">
            <h3>请假申请</h3>
          </header>
          <!-- 1. 绑定表单规则和ref，用于验证 -->
          <el-form :model="formData" :rules="rules" ref="formRef" hide-required-asterisk label-width="100px">
            <el-row style="display: flex; justify-content: space-evenly; margin-bottom: 20px;">
              <!-- 2. 为每个表单项添加prop，关联验证规则 -->
              <el-form-item label="姓名" prop="userName" style="margin-left: 2em;">
                <el-input v-model="formData.userName" disabled></el-input>
              </el-form-item>
              <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker v-model="formData.beginTime" type="date" placeholder="请选择开始时间" style="width: 200px;"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row style="display: flex; justify-content: space-evenly; margin-bottom: 20px;">
              <el-form-item label="标识" prop="roleName" style="margin-left: 2em;">
                <el-input v-model="formData.roleName" disabled></el-input>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="formData.endTime" type="date" placeholder="请选择结束时间" style="width: 200px;"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row style="margin-left: 60px; margin-bottom: 20px;">
              <el-form-item label="请假事由" prop="reason">
                <el-input v-model="formData.reason" placeholder="请输入请假事由"></el-input>
              </el-form-item>
            </el-row>
            <!-- 3. 新增请假时长字段（自动计算，用于提交和验证）
            <el-row style="margin-left: 60px; margin-bottom: 20px;">
              <el-form-item label="请假时长(天)" prop="totalTime">
                <el-input v-model="formData.totalTime" placeholder="自动计算" readonly></el-input>
              </el-form-item>
            </el-row> -->
            <el-row class="footer" style="display: flex; justify-content: space-evenly;">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="sure">确认</el-button>
            </el-row>
          </el-form>
        </el-dialog>
      </div>
    </div>
    <div class="content">
      <el-table :data="tableData" style="width: 90% ;border-radius: 20px;margin: 0 auto;">
        <el-table-column prop="userName" label="姓名" align="center" />
        <el-table-column prop="roleName" label="职能" align="center" />
        <el-table-column prop="reason" label="请假事由" align="center" />
        <el-table-column prop="beginTime" label="开始时间" align="center" />
        <el-table-column prop="endTime" label="结束时间" align="center" />
        <el-table-column prop="totalTime" label="请假时长(天)" align="center" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <div :class="{
              'reviewing': scope.row.status === '正在审核中',
              'reviewing2': scope.row.status === '不通过',
              'reviewing3': scope.row.status === '通过'
            }">
              {{ scope.row.status }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" #default="scoped">
          <div style="display: flex;justify-content: space-evenly;">
            <p style="color: green;" @click="change(scoped.row)">修改</p>
            <p style="color: red;" @click="del(scoped.row)">撤销</p>
            <p style="color: blue;" @click=detail(scoped.row)>详情</p>
            <el-drawer v-model="drawer" :modal="false" title="请假详情信息" style="margin-top: 80px;" :showClose="false">
              <el-row>
                <div class="richang">
                  <div class="name">
                    <span class="name1">姓 名：</span>
                    <span class="name2">{{ selectedRow.userName }}</span>
                  </div>
                  <div class="name">
                    <span class="name1">职 能：</span>
                    <span class="name2">{{ selectedRow.roleName }}</span>
                  </div>
                  <div class="name">
                    <span >开始时间：</span>
                    <span class="name2">{{ selectedRow.beginTime }}</span>
                  </div>
                  <div class="name">
                    <span class="date1">结束时间：</span>
                    <span class="date2">{{ selectedRow.endTime }}</span>
                  </div>
                  <div class="name">
                    <span class="name1">请假时长：</span>
                    <span class="name2">{{ selectedRow.totalTime }}</span>
                  </div>
                  <div class="name">
                    <span class="name1">状 态：</span>
                    <span :class="{
                      'reviewing': selectedRow.status === '正在审核中',
                      'reviewing2': selectedRow.status === '不通过',
                      'reviewing3': selectedRow.status === '通过'
                    }">{{ selectedRow.status }}</span>
                  </div>
                  <div class="name">
                    <span class="content1">请假事由：</span>
                    <span class="content2">{{ selectedRow.reason }}</span>
                  </div>
                </div>
              </el-row>
              <el-button style="margin-left: 450px;margin-top: 250px;" @click="drawer = false">关闭</el-button>
            </el-drawer>
          </div>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage"
          :page-size="pageSize" @current-change="handleCurrentPageChange" />
        <div>
          每页
          <el-input-number v-model="pageSize" :min="1" :max="30" controls-position="right" @change="handleChange" />条
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDay, getDayInfo } from '../api/Daily'
import { getLeave, getIdentity, postLeave, getLeaveInfo, updateLeave, revokeLeave } from '../api/Leave'
import { getBusiness, getBusinessInfo, addBusiness } from '../api/Business'
import '@/assets/css/businesstripdiary.css'
import { reactive, ref } from 'vue'
import { ElDialog, ElButton } from 'element-plus';
// 4. 引入dayjs用于时间计算和校验
import dayjs from 'dayjs'

// 定义当前年月
const currentYearMonth = ref('')
// 定义日期选择器的引用
const datePickerRef = ref(null)
//搜搜
const classSearchInput = ref('')
//定义falg判断删除还是修改
let flag = 1;
let drawer = ref(false)
// 5. 表单ref：用于触发验证
const formRef = ref(null)

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 切换年月时重置当前页码
  if (roleId == 3 || roleId == 5|| roleId == 4) {
    fetchData2()
  } else {
    fetchData()
  }
}
//修改：修复表单赋值方式（避免直接覆盖响应式对象）
let change = (v) => {
  flag = 2
  dialogVisible.value = true
  // 6. 深拷贝赋值，保留响应式
  formData.userName = v.userName
  formData.roleName = v.roleName
  formData.beginTime = v.beginTime
  formData.endTime = v.endTime
  formData.reason = v.reason
  formData.totalTime = v.totalTime
  formData.status = v.status
  formData.leaveId = v.leaveId
}
let selectedRow = ref('')
//详情
let detail = (v) => {
  drawer.value = true
  selectedRow = v
}
//撤销
let del = (v) => {
  const data = {
    leaveId: v.leaveId, // 请假ID
  }
  revokeLeave('deleteLeave', data).then((res) => {
    if (res.code == 200) {
      ElMessage.success('撤销成功')
      if (roleId == '1' || roleId == '2') {
        fetchData()
      } else {
        fetchData2()
      }
    }
  })
}
// 处理页码变化
const handleCurrentPageChange = (page) => {
  currentPage.value = page // 更新当前页码
  if (roleId == 3 || roleId == 5 ) {
    fetchData2()
  } else {
    fetchData()
  }
}
function handleChange() {
  currentPage.value = 1; // 切换每页显示的数量时重置当前页码
  if (roleId == 3 || roleId == 5) {
    fetchData2()
  } else {
    fetchData()
  }
}
let dialogVisible = ref(false)
//获取身份：转为字符串避免类型判断错误
let roleId = sessionStorage.getItem('roleId') + ''
//当前页
let currentPage = ref(1)
//每个个数
let pageSize = ref(4)
//个数
let total = ref(1)
//数据
let tableData = ref([
  {
    reason: '',
    roleName: '',
    beginTime: '',
    endTime: '',
    totalTime: '',
    status: '',
    userName: '',
    leaveId: ''
  }
])
// 7. 修复表单数据：改为对象类型（原数组类型不适合单个表单）
let formData = reactive({
  reason: '',
  roleName: '',
  beginTime: '',
  endTime: '',
  totalTime: '',
  status: '正在审核中', // 默认状态：正在审核中
  userName: '',
  leaveId: '' // 用于修改时传递请假ID
})

// 8. 时间校验逻辑1：开始时间不能晚于结束时间
const validateBeginTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择开始时间'))
    return
  }
  // 若结束时间已选择，判断时间顺序
  if (formData.endTime) {
    const begin = dayjs(value)
    const end = dayjs(formData.endTime)
    if (begin.isAfter(end)) {
      callback(new Error('开始时间不能晚于结束时间'))
    } else {
      calculateTotalTime() // 自动计算时长
      callback()
    }
  } else {
    callback()
  }
}

// 9. 时间校验逻辑2：结束时间不能早于开始时间
const validateEndTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择结束时间'))
    return
  }
  // 若开始时间已选择，判断时间顺序
  if (formData.beginTime) {
    const begin = dayjs(formData.beginTime)
    const end = dayjs(value)
    if (end.isBefore(begin)) {
      callback(new Error('结束时间不能早于开始时间'))
    } else {
      calculateTotalTime() // 自动计算时长
      callback()
    }
  } else {
    callback()
  }
}

// 10. 自动计算请假时长（包含首尾天，如1号-2号算2天）
const calculateTotalTime = () => {
  if (formData.beginTime && formData.endTime) {
    const begin = dayjs(formData.beginTime)
    const end = dayjs(formData.endTime)
    const days = end.diff(begin, 'day') + 1
    formData.totalTime = days.toString()
  }
}

// 11. 表单验证规则：关联所有必填项和自定义校验
const rules = ref({
  userName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  // roleName: [
  //   { required: true, message: '标识不能为空', trigger: 'blur' }
  // ],
  beginTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateBeginTime, trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' },
    { min: 2, max: 200, message: '请假事由长度需在2-200字之间', trigger: 'blur' }
  ],
  totalTime: [
    { required: true, message: '请选择完整的时间范围（自动计算）', trigger: 'change' },
    { type: 'number', message: '请假时长必须为数字', trigger: 'change' },
    { min: 0.5, message: '请假时长不能小于0.5天', trigger: 'change' } // 支持半天请假
  ]
})

//管理员查看出差
async function fetchData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  await getLeave("leavesList", data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.leaveList || []
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}
// 12. 提交表单：先执行验证，通过后再调用接口
function sure() {
  // 触发表单验证
  formRef.value.validate((valid) => {
    if (!valid) {
      return // 验证失败，不提交
    }

    // 验证通过，构造提交数据
    let data = {
      userId: Number(sessionStorage.getItem('userId')),
      reason: formData.reason,
      roleName: formData.roleName,
      beginTime: formData.beginTime,
      endTime: formData.endTime,
      totalTime: Number(formData.totalTime), // 转为数字提交
      status: formData.status,
      userName: formData.userName,
      roleId: Number(roleId),
      leaveId: formData.leaveId || '' // 修改时必传，新增时可选
    }

    // 新增逻辑
    if (flag == 1) {
      postLeave('addLeave', data).then((res) => {
        if (res.code == 200) {
          ElMessage.success('请假申请提交成功')
          dialogVisible.value = false
          fetchData2() // 重新拉取个人请假记录
          formRef.value.resetFields() // 重置表单
        } else {
          ElMessage.error('提交失败：' + res.msg)
        }
      })
    } 
    // 修改逻辑
    else if (flag == 2) {
      updateLeave('updateLeave', data).then((res) => {
        if (res.code == 200) {
          ElMessage.success('请假信息修改成功')
          dialogVisible.value = false
          fetchData2() // 重新拉取个人请假记录
          formRef.value.resetFields() // 重置表单
        } else {
          ElMessage.error('修改失败：' + res.msg)
        }
      })
    }
  })
}
//点击申请：重置表单状态
function apply() {
  flag = 1;
  dialogVisible.value = true
  // 重置表单（避免残留修改数据）
  formRef.value?.resetFields()
  // 重置默认状态
  formData.status = '正在审核中'
}
let userId = sessionStorage.getItem('userId')
//老师查看个人请假记录
function fetchData2() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    userId: Number(userId),
    roleId: Number(roleId)
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getLeaveInfo('leavesListPersonal', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.leaveList || []
      
      // 初始化表单的roleName（从第一条数据获取，若有）
      if (tableData.value.length > 0) {
        formData.roleName = tableData.value[0].roleName
      }
      total.value = res.dataset.pageCount * pageSize.value
      
    }
  })
}
// 页面挂载：初始化姓名（优先用userName，次之role）
onMounted(() => {
  formData.userName = sessionStorage.getItem('userName') || sessionStorage.getItem('role') || ''
  
  
  if (roleId == '3' || roleId == '5' ||roleId=='4') {
    fetchData2()
  } else {
    fetchData()
  }
})
</script>

<style lang="less" scoped>
.reviewing {
  color: #007bff;
}

.reviewing2 {
  color: red;
}

.reviewing3 {
  color: green;
}
/* 补充表单样式，优化显示 */
.el-form-item {
  margin-bottom: 15px;
}
.el-dialog__body {
  padding: 20px 30px;
}
.richang {
  padding: 20px;
}
.name {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.name1, .date1, .content1 {
  width: 80px;
  text-align: right;
  margin-right: 10px;
  font-weight: 500;
}
</style>